package com.psq.core.common.base

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.psq.core.common.model.BaseViewModel
import com.psq.core.common.ui.dialog.ExceptionDialog
import java.lang.reflect.ParameterizedType

abstract class BaseVMFragment<VM : BaseViewModel> : BaseFragment() {

    lateinit var viewModel: VM

    override fun doBeforeView(savedInstanceState: Bundle?) {
        super.doBeforeView(savedInstanceState)
        initViewModel()
    }

    override fun doAfterView(savedInstanceState: Bundle?) {
        super.doAfterView(savedInstanceState)
        viewModel.start()
    }

    @Suppress("UNCHECKED_CAST")
    private fun initViewModel() {
        // 获取类泛型类型
        val type: Class<VM> =
            (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
        viewModel = ViewModelProvider(this)[type]
        viewModel.exception.observe(this) {
            Log.e(
                javaClass.simpleName,
                "find an Exception on ${viewModel.javaClass.simpleName} : $it"
            )
            onException(it)
        }
    }

    open fun onException(exception: Exception) {
        requireActivity().apply {
            ExceptionDialog(exception).show(supportFragmentManager)
        }
    }

}